<template>
  <div class="user-reservations">
    <a-card title="我的预约" class="reservations-card">
      <!-- 快速统计 -->
      <div class="stats-section">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-statistic title="待确认" :value="pendingCount" />
          </a-col>
          <a-col :span="8">
            <a-statistic title="已确认" :value="confirmedCount" />
          </a-col>
          <a-col :span="8">
            <a-statistic title="总预约" :value="totalCount" />
          </a-col>
        </a-row>
      </div>

      <!-- 筛选器 -->
      <div class="filter-section">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-select
              v-model:value="filterStatus"
              placeholder="选择状态"
              @change="applyFilter"
              style="width: 100%"
            >
              <a-select-option value="">全部状态</a-select-option>
              <a-select-option value="pending">待确认</a-select-option>
              <a-select-option value="confirmed">已确认</a-select-option>
              <a-select-option value="cancelled">已取消</a-select-option>
              <a-select-option value="completed">已完成</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="8">
            <a-select
              v-model:value="filterType"
              placeholder="预约类型"
              @change="applyFilter"
              style="width: 100%"
            >
              <a-select-option value="">全部类型</a-select-option>
              <a-select-option value="1">场馆预约</a-select-option>
              <a-select-option value="2">场地预约</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="8">
            <a-button type="primary" @click="loadReservations" :loading="loading">
              刷新
            </a-button>
          </a-col>
        </a-row>
      </div>

      <!-- 预约列表 -->
      <div class="reservations-list">
        <a-spin :spinning="loading">
          <div v-if="filteredReservations.length === 0" class="empty-state">            <a-empty description="暂无预约记录">
              <a-button type="primary" @click="$router.push('/gym')">
                前往场馆详情页预约
              </a-button>
            </a-empty>
          </div>
          
          <div v-else class="reservation-cards">
            <a-card
              v-for="reservation in filteredReservations"
              :key="reservation.reservationId"
              class="reservation-item"
              :class="{ 'pending': reservation.status === 'pending' }"
            >
              <template #title>
                <div class="card-title">
                  <span class="gym-name">{{ reservation.gymName }}</span>
                  <a-tag :color="getTypeColor(reservation.reservationType)">
                    {{ getTypeText(reservation.reservationType) }}
                  </a-tag>
                </div>
              </template>
              
              <template #extra>
                <a-tag :color="getStatusColor(reservation.status)">
                  {{ getStatusText(reservation.status) }}
                </a-tag>
              </template>

              <div class="reservation-content">
                <div class="reservation-info">
                  <a-row :gutter="16">
                    <a-col :span="12">
                      <div class="info-item">
                        <a-icon type="calendar" />
                        <span>{{ reservation.reservationDate }}</span>
                      </div>
                    </a-col>
                    <a-col :span="12">
                      <div class="info-item">
                        <a-icon type="clock-circle" />
                        <span>{{ reservation.timeSlot }}</span>
                      </div>
                    </a-col>
                    <a-col v-if="reservation.areaType" :span="12">
                      <div class="info-item">
                        <a-icon type="environment" />
                        <span>{{ reservation.areaType }}</span>
                      </div>
                    </a-col>
                    <a-col :span="12">
                      <div class="info-item">
                        <a-icon type="calendar" />
                        <span>{{ formatDateTime(reservation.createTime) }}</span>
                      </div>
                    </a-col>
                  </a-row>
                </div>

                <div v-if="reservation.description" class="description">
                  <strong>使用说明：</strong>{{ reservation.description }}
                </div>

                <div class="actions">
                  <a-space>
                    <a-button
                      v-if="reservation.status === 'pending' || reservation.status === 'confirmed'"
                      danger
                      size="small"
                      @click="cancelReservation(reservation.reservationId)"
                    >
                      取消预约
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      @click="viewDetails(reservation)"
                    >
                      查看详情
                    </a-button>
                    <a-button
                      v-if="reservation.sessionId"
                      type="primary"
                      size="small"
                      @click="goToChat(reservation.sessionId)"
                    >
                      查看聊天
                    </a-button>
                  </a-space>
                </div>
              </div>
            </a-card>
          </div>
        </a-spin>
      </div>
    </a-card>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:open="detailVisible"
      title="预约详情"
      :footer="null"
      width="600px"
    >
      <div v-if="selectedReservation" class="detail-content">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="场馆名称">
            {{ selectedReservation.gymName }}
          </a-descriptions-item>
          <a-descriptions-item label="预约类型">
            <a-tag :color="getTypeColor(selectedReservation.reservationType)">
              {{ getTypeText(selectedReservation.reservationType) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="预约状态">
            <a-tag :color="getStatusColor(selectedReservation.status)">
              {{ getStatusText(selectedReservation.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="预约日期">
            {{ selectedReservation.reservationDate }}
          </a-descriptions-item>
          <a-descriptions-item label="预约时段">
            {{ selectedReservation.timeSlot }}
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedReservation.areaType" label="预约区域">
            {{ selectedReservation.areaType }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatDateTime(selectedReservation.createTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ formatDateTime(selectedReservation.updateTime) }}
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedReservation.description" label="使用说明" :span="2">
            {{ selectedReservation.description }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import http from '@/utils/http'
import dayjs from 'dayjs'

const router = useRouter()

// 响应式数据
const reservations = ref([])
const loading = ref(false)
const detailVisible = ref(false)
const selectedReservation = ref(null)
const filterStatus = ref('')
const filterType = ref('')

// 计算属性
const pendingCount = computed(() => {
  return reservations.value.filter(r => r.status === 'pending').length
})

const confirmedCount = computed(() => {
  return reservations.value.filter(r => r.status === 'confirmed').length
})

const totalCount = computed(() => {
  return reservations.value.length
})

const filteredReservations = computed(() => {
  let result = reservations.value

  if (filterStatus.value) {
    result = result.filter(r => r.status === filterStatus.value)
  }

  if (filterType.value) {
    result = result.filter(r => r.reservationType === parseInt(filterType.value))
  }

  // 按创建时间倒序排列
  return result.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
})

// 方法
const loadReservations = async () => {
  loading.value = true
  try {
    const response = await http.get('/v1/reservation/user')
    
    if (response.data.code === 2000) {
      reservations.value = response.data.data || []
    } else {
      message.error(response.data.msg || '加载预约记录失败')
    }
  } catch (error) {
    console.error('加载预约记录失败:', error)
    message.error('加载预约记录失败')
  } finally {
    loading.value = false
  }
}

const cancelReservation = (reservationId) => {
  Modal.confirm({
    title: '确认取消预约？',
    content: '取消后无法恢复，确定要取消这个预约吗？',
    onOk: async () => {
      try {
        const response = await http.put(`/v1/reservation/${reservationId}/cancel`)
        
        if (response.data.code === 2000) {
          message.success('预约已取消')
          loadReservations()
        } else {
          message.error(response.data.msg || '取消预约失败')
        }
      } catch (error) {
        console.error('取消预约失败:', error)
        message.error('取消预约失败')
      }
    }
  })
}

const viewDetails = (reservation) => {
  selectedReservation.value = reservation
  detailVisible.value = true
}

const goToChat = (sessionId) => {
  router.push({
    path: '/chat',
    query: { sessionId }
  })
}

const applyFilter = () => {
  // 筛选在计算属性中自动应用
}

const getTypeColor = (type) => {
  return type === 1 ? 'blue' : 'green'
}

const getTypeText = (type) => {
  return type === 1 ? '场馆预约' : '场地预约'
}

const getStatusColor = (status) => {
  const colorMap = {
    pending: 'orange',
    confirmed: 'green',
    cancelled: 'red',
    completed: 'blue'
  }
  return colorMap[status] || 'default'
}

const getStatusText = (status) => {
  const textMap = {
    pending: '待确认',
    confirmed: '已确认',
    cancelled: '已取消',
    completed: '已完成'
  }
  return textMap[status] || status
}

const formatDateTime = (dateTime) => {
  return dateTime ? dayjs(dateTime).format('MM-DD HH:mm') : ''
}

// 生命周期
onMounted(() => {
  loadReservations()
})
</script>

<style scoped>
.user-reservations {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.reservations-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.reservations-list {
  min-height: 200px;
}

.reservation-cards {
  display: grid;
  gap: 16px;
}

.reservation-item {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.reservation-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.reservation-item.pending {
  border-left: 4px solid #faad14;
}

.card-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.gym-name {
  font-weight: 600;
  font-size: 16px;
}

.reservation-content {
  padding-top: 8px;
}

.reservation-info {
  margin-bottom: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  color: #666;
}

.info-item .anticon {
  margin-right: 8px;
  color: #1890ff;
}

.description {
  background: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  margin-bottom: 12px;
  font-size: 14px;
  line-height: 1.5;
}

.actions {
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
  display: flex;
  justify-content: flex-end;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.detail-content {
  padding: 16px 0;
}

@media (max-width: 768px) {
  .user-reservations {
    padding: 10px;
  }
  
  .stats-section,
  .filter-section {
    padding: 12px;
  }
  
  .reservation-cards {
    gap: 12px;
  }
  
  .info-item {
    font-size: 13px;
  }
}
</style>
